/**
 * Created by zhangyilin on 2018/11/13.
 */
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/***
 *
 * 登录匹配
 *
 */

public class Group extends HttpServlet {
    private String InviteID;//邀请码
    private String ClassName;
    private String ClassBlonger;
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
            throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("text/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("UTF-8");//setContentType与setCharacterEncoding的顺序不能调换，否则还是无法解决中文乱码的问
        ClassName = request.getParameter("classname");//班级名称
        System.out.println(ClassName);
        ClassBlonger =(String) request.getSession().getAttribute("ID");
        System.out.println((String) request.getSession().getAttribute("ID"));


//        ClassBlonger = request.getParameter("classowner");//班级创建者,Web会话获取创建者ID，测试阶段自行输入
        String range = "0123456789abcdefghijklmnopqrstuvwxyz";//随机邀请码取值范围
        Random random = new Random();
        StringBuilder tempID = null;
        do {
            tempID = new StringBuilder();//StringBuilder类临时邀请码，也可使用StringBuffer
            for ( int i = 0; i < 6; i++ ){//生成6位随机码
                tempID.append(range.charAt(random.nextInt(range.length())));
            }
        }while(existed(tempID.toString()));//邀请码已被使用，重新生成
        InviteID = tempID.toString();//toString将StringBuilder类型内容转存为String类型
//        setClassName(ClassName);
//        setClassBlonger(ClassBlonger);
//        setInviteID(InviteID);
//        HttpSession session = request.getSession();
        Connection conn = GetConnection();
        String sql = "insert into Class_t values(\""+InviteID+"\",\""+ClassName+"\",\""+ClassBlonger+"\")";
        Statement sta = null;
//        String answer = "0";

        try {
            if(conn != null)
                sta = conn.createStatement();
            if(sta != null) {
                sta.execute(sql);
//                answer="1";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
//                out.write(answer);
//                out.close();
                if(sta != null)
                    sta.close();
                if(conn != null)
                    conn.close();
//                sta = null;
//                conn = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    public Connection GetConnection() {//与数据库建立连接
        String url = "jdbc:mysql://localhost:3306/listsystem";//与本机的3306端口建立连接，进入数据库listsystem
        String driverName = "com.mysql.jdbc.Driver";//驱动注册
        String userName = "root";
        String password = "";
        Connection conn = null;//用于建立与数据库的连接
        try{
            Class.forName(driverName);// jdbc4.0 后无需使用这句进行驱动注册操作
            conn = DriverManager.getConnection(url, userName, password);
        }catch(Exception e){
            System.out.println(e);
        }
        return conn;
    }



    private boolean existed(String ID) {//判断邀请码是否已使用
        Connection conn = GetConnection();
        String sql = "select InviteID from Class_t";
        ResultSet rs = null;
        Statement sta = null;
        List<String> IDlist = new ArrayList<>();//存放数据库中InvietID信息
        try {
            if(conn != null)
                sta = conn.createStatement();
            if(sta != null)
                rs = sta.executeQuery(sql);
            while(rs != null && rs.next()) {
                IDlist.add(rs.getString("InviteID"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(rs != null)
                    rs.close();
                if(sta != null)
                    sta.close();
                if(conn != null)
                    conn.close();
                rs = null;
                sta = null;
                conn = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(IDlist.contains(ID))
            return true;
        return false;
    }

    public String getClassName() {
        return ClassName;
    }
    public void setClassName(String className) {
        ClassName = className;
    }
    public String getClassBlonger() {
        return ClassBlonger;
    }
    public void setClassBlonger(String classBlonger) {
        ClassBlonger = classBlonger;
    }
    public String getInviteID() {
        return InviteID;
    }
    public void setInviteID(String inviteID) {
        InviteID = inviteID;
    }

    @Override
    public String toString() {
        return "<html>"
                + "<head>"
                + "<title>创建成功</title>"
                + "</head>"
                + "<body>"
                + "<center>"
                + "Group [ClassName=" + getClassName() + ", ClassBlonger=" + getClassBlonger() + ", InviteID=" + InviteID + "]"+"<br>"
                + "<input type=\"button\" value=\"返回\" onclick=\"window.location.href='index10.jsp'\"/>"
                + "</cennter>"
                + "</body>"
                + "</html>";
    }
}
